import React, { memo, useState } from 'react'
import type { FC, ReactNode } from 'react'
import { Tabs, ConfigProvider } from 'antd'

import styles from './index.module.scss'
import EditorViewer from '../../EditorViewer'

import { useMySelector, MyShallEqual, useMyDispatch } from '../../../store'
import { setCopyCode, setFocusLanguage } from '../../../store/modules/success'

// type TargetKey = React.MouseEvent | React.KeyboardEvent | string

interface CodeItem {
  key: string
  label: string
  codeSlice: string
  language: string
}

interface IProps {
  children?: ReactNode
}

const CodeViewer: FC<IProps> = () => {
  const dispatch = useMyDispatch()
  const { codeall } = useMySelector(
    (state) => ({
      codeall: state.codeall.codeAll
    }),
    MyShallEqual
  ) as { codeall: CodeItem[] }

  const initialItems =
    codeall && codeall.length > 0
      ? codeall.map((item) => ({
          ...item,
          closable: false,
          children: <EditorViewer code={item.codeSlice} />
        }))
      : []

  const [activeKey, setActiveKey] = useState(
    initialItems.length > 0 ? initialItems[0].key : ''
  )

  const onChange = (newActiveKey: string) => {
    const content = initialItems.find((item) => item.key === newActiveKey)
    if (content) {
      dispatch(setCopyCode(content?.codeSlice))
      dispatch(setFocusLanguage(content?.language))
      setActiveKey(newActiveKey)
    }
  }

  return (
    <ConfigProvider
      theme={{
        token: {
          colorPrimary: '#00b96b',
          colorText: '#fff',
          controlHeight: 20
        },
        components: {
          Tabs: {
            cardGutter: 8, // 调整卡片间距
            colorIcon: '#fff'
          }
        }
      }}
    >
      <Tabs
        type="card"
        onChange={onChange}
        activeKey={activeKey}
        items={initialItems}
        className={styles.codeselector}
      />
    </ConfigProvider>
  )
}

export default memo(CodeViewer)
